package br.edu.sistemaacademico.observer;

import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

public class ValidaCTPS extends ValidaTelefone{

    public ValidaCTPS() {
    }    

    public void remove(final Observavel o){
        SwingUtilities.invokeLater(new Runnable() {
        public void run() {
         Document d = o.getDocument();
                 try {
                	 if(o.getDocument().getLength()>=1)
                	 d.remove(o.getDocument().getLength()-1,1);
                 } catch (BadLocationException ex) {
                     Logger.getLogger(ValidaTelefone.class.getName()).log(Level.SEVERE, null, ex);
                 }
                 	
          o.setDocument(d);
         }
     });
 }

 public void update(final Observavel o, Object arg) {
     try {
     String document =  o.getDocument().getText(0, o.getDocument().getLength());
     char character; 
     Pattern patter = Pattern.compile("[0-9]");
     if(o.getDocument().getLength()<1)
     character = o.getDocument().getText(0, 1).charAt(0);
     else
     character = o.getDocument().getText(0, o.getDocument().getLength()).charAt(o.getDocument().getLength()-1);
     Matcher matcher = patter.matcher(String.valueOf(character));
     if(!matcher.find()||o.getDocument().getLength()>=9)
             remove(o);
     } catch (BadLocationException ex) {
         Logger.getLogger(ValidaTelefone.class.getName()).log(Level.SEVERE, null, ex);
     }
 }
 public void formata(final Observavel o){
     SwingUtilities.invokeLater(new Runnable() {
     public void run() {
      Document d = o.getDocument();
              try {
             	 if(o.getDocument().getLength()==3)
                  d.insertString(d.getLength()-1, ".", null);
              } catch (BadLocationException ex) {
                  Logger.getLogger(ValidaTelefone.class.getName()).log(Level.SEVERE, null, ex);
              }
              	
       o.setDocument(d);
      }
  });
}
}
